"""
数据库模型定义
"""
from datetime import datetime
from typing import Optional, Dict, Any
from sqlalchemy import Column, Integer, String, DateTime, Boolean, Text, ForeignKey, Float
from sqlalchemy.orm import relationship
from sqlalchemy.dialects.sqlite import JSON
import json
from .base import Base


class User(Base):
    """用户表"""
    __tablename__ = "users"
    
    id = Column(Integer, primary_key=True, index=True)
    username = Column(String(50), unique=True, index=True, nullable=False)
    password_hash = Column(String(255), nullable=False)
    email = Column(String(100), unique=True, index=True, nullable=False)
    role = Column(String(20), default="user")  # admin, user
    created_at = Column(DateTime, default=datetime.now)
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
    is_active = Column(Boolean, default=True)
    last_login = Column(DateTime)
    
    # 关系
    parse_tasks = relationship("ParseTask", back_populates="user")
    api_logs = relationship("APILog", back_populates="user")


class ParseTask(Base):
    """解析任务表"""
    __tablename__ = "parse_tasks"
    
    id = Column(Integer, primary_key=True, index=True)
    task_id = Column(String(100), unique=True, index=True, nullable=False)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
    filename = Column(String(255), nullable=False)
    file_path = Column(String(500), nullable=False)
    file_size = Column(Integer, nullable=False)
    status = Column(String(20), default="pending", index=True)  # pending, processing, completed, failed
    progress = Column(Integer, default=0)
    created_at = Column(DateTime, default=datetime.now, index=True)
    started_at = Column(DateTime)
    completed_at = Column(DateTime)
    error_message = Column(Text)
    result_path = Column(String(500))
    execution_mode = Column(String(10), default="async")  # sync, async
    parse_options = Column(JSON)  # 解析选项
    priority = Column(Integer, default=5)  # 任务优先级 1-9，1为最高，9为最低
    
    # 关系
    user = relationship("User", back_populates="parse_tasks")
    parse_results = relationship("ParseResult", back_populates="task")
    slice_tasks = relationship("SliceTask", back_populates="parse_task")


class ParseResult(Base):
    """解析结果表"""
    __tablename__ = "parse_results"
    
    id = Column(Integer, primary_key=True, index=True)
    task_id = Column(Integer, ForeignKey("parse_tasks.id"), nullable=False)
    content_type = Column(String(20), nullable=False)  # text, markdown, layout, images
    content_path = Column(String(500), nullable=False)
    file_size = Column(Integer)
    created_at = Column(DateTime, default=datetime.now)
    result_metadata = Column(JSON)  # 元数据信息
    
    # 关系
    task = relationship("ParseTask", back_populates="parse_results")


class SliceTask(Base):
    """切片任务表"""
    __tablename__ = "slice_tasks"
    
    id = Column(Integer, primary_key=True, index=True)
    slice_id = Column(String(100), unique=True, index=True, nullable=False)
    parse_task_id = Column(Integer, ForeignKey("parse_tasks.id"), nullable=False)
    status = Column(String(20), default="pending")  # pending, processing, completed, failed
    strategy = Column(String(20), nullable=False)  # semantic, paragraph, fixed
    chunk_size = Column(Integer, default=1000)
    overlap = Column(Integer, default=200)
    min_chunk_size = Column(Integer, default=100)
    total_chunks = Column(Integer, default=0)
    created_at = Column(DateTime, default=datetime.now)
    completed_at = Column(DateTime)
    result_path = Column(String(500))
    error_message = Column(Text)
    
    # 关系
    parse_task = relationship("ParseTask", back_populates="slice_tasks")
    slice_chunks = relationship("SliceChunk", back_populates="slice_task")


class SliceChunk(Base):
    """切片块表"""
    __tablename__ = "slice_chunks"
    
    id = Column(Integer, primary_key=True, index=True)
    slice_task_id = Column(Integer, ForeignKey("slice_tasks.id"), nullable=False)
    chunk_id = Column(String(100), nullable=False)
    text_content = Column(Text, nullable=False)
    word_count = Column(Integer, default=0)
    page_number = Column(Integer)
    position_info = Column(JSON)
    chunk_metadata = Column(JSON)
    created_at = Column(DateTime, default=datetime.now)
    
    # 关系
    slice_task = relationship("SliceTask", back_populates="slice_chunks")


class APILog(Base):
    """API调用日志表"""
    __tablename__ = "api_logs"
    
    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=True)
    endpoint = Column(String(255), nullable=False)
    method = Column(String(10), nullable=False)
    request_data = Column(JSON)
    response_data = Column(JSON)
    status_code = Column(Integer)
    response_time = Column(Float)  # 响应时间（秒）
    ip_address = Column(String(45))
    user_agent = Column(Text)
    created_at = Column(DateTime, default=datetime.now,index=True)
    
    # 关系
    user = relationship("User", back_populates="api_logs")


class SystemConfig(Base):
    """系统配置表"""
    __tablename__ = "system_configs"
    
    id = Column(Integer, primary_key=True, index=True)
    config_key = Column(String(100), unique=True, nullable=False)
    config_value = Column(Text, nullable=False)
    description = Column(Text)
    created_at = Column(DateTime, default=datetime.now)
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)


class TokenBlacklist(Base):
    """Token黑名单表"""
    __tablename__ = "token_blacklist"
    
    id = Column(Integer, primary_key=True, index=True)
    token = Column(String(500), unique=True, nullable=False)
    expires_at = Column(DateTime, nullable=False)
    created_at = Column(DateTime, default=datetime.now)


class SystemMetrics(Base):
    """系统监控指标表"""
    __tablename__ = "system_metrics"
    
    id = Column(Integer, primary_key=True, index=True)
    cpu_percent = Column(Float, nullable=False)
    memory_percent = Column(Float, nullable=False)
    memory_used = Column(Integer, nullable=False)  # MB
    memory_total = Column(Integer, nullable=False)  # MB
    disk_percent = Column(Float, nullable=False)
    disk_used = Column(Integer, nullable=False)  # GB
    disk_total = Column(Integer, nullable=False)  # GB
    load_average = Column(Float)  # 系统负载
    uptime = Column(Integer, nullable=False)  # 秒
    network_sent = Column(Integer, default=0)  # KB
    network_recv = Column(Integer, default=0)  # KB
    process_count = Column(Integer, default=0)
    thread_count = Column(Integer, default=0)
    status = Column(String(20), default="normal")  # normal, warning, critical
    timestamp = Column(DateTime, default=datetime.now, index=True)